<?php

namespace app\admin\controller\newhouse;

use app\common\controller\Backend;

/**
 * 新房结构管理
 *
 * @icon fa fa-circle-o
 */
class Structure extends Backend
{

    /**
     * NewhouseStructure模型对象
     * @var \app\common\model\NewhouseStructure
     */
    protected $model = null;
    protected $multiFields = 'flag,price';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\NewhouseStructure;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("flagList", $this->model->getFlagList());
        $this->view->assign("priceList", $this->model->getPriceList());
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->with(['newhousecategory','newhouse','salelabel','ambientlabel'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->with(['newhousecategory','newhouse','salelabel','ambientlabel'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                $row->visible(['id','flag','price','title','status','createtime','updatetime']);
                $row->visible(['newhousecategory']);
				$row->getRelation('newhousecategory')->visible(['name']);
				$row->visible(['newhouse']);
				$row->getRelation('newhouse')->visible(['title']);
				$row->visible(['salelabel']);
				$row->getRelation('salelabel')->visible(['name']);
				$row->visible(['ambientlabel']);
				$row->getRelation('ambientlabel')->visible(['name']);
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $count = $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();
            $count = 0;
            foreach ($list as $k => $v) {
                // 判断是否有楼栋
                $NewhouseBuilding = model('NewhouseBuilding');
                $building = $NewhouseBuilding->get(['structure_id' => $v['id']]);
                if ($building) {
                    $this->error(__('You can not delete that contain child'));
                }

                // 删除楼盘图片
                if ($v['cover_image']) {
                    $attachmentFile = ROOT_PATH . '/public/uploads' . $v['cover_image'];
                    if (is_file($attachmentFile))
                    {
                        @unlink($attachmentFile);
                    }
                    //同步删除oss
                    $ftpcfg = get_addon_config('ftp');
                    if ($ftpcfg['ftp_usernmae'] && $ftpcfg['ftp_password']) {
                        $FTP = new \addons\ftp\library\Auth($ftpcfg['ftp_host'], $ftpcfg['ftp_port'], $ftpcfg['ftp_usernmae'], $ftpcfg['ftp_password'], $ftpcfg['ftp_ssh'], $ftpcfg['ftp_pasv']);
                        $FTP->del_file(str_replace('/', DIRECTORY_SEPARATOR, $v['cover_image']));
                        $FTP->close();
                    }
                }
                if ($v['3d_image']) {
                    $attachmentFile = ROOT_PATH . '/public/uploads' . $v['3d_image'];
                    if (is_file($attachmentFile))
                    {
                        @unlink($attachmentFile);
                    }
                    //同步删除oss
                    $ftpcfg = get_addon_config('ftp');
                    if ($ftpcfg['ftp_usernmae'] && $ftpcfg['ftp_password']) {
                        $FTP = new \addons\ftp\library\Auth($ftpcfg['ftp_host'], $ftpcfg['ftp_port'], $ftpcfg['ftp_usernmae'], $ftpcfg['ftp_password'], $ftpcfg['ftp_ssh'], $ftpcfg['ftp_pasv']);
                        $FTP->del_file(str_replace('/', DIRECTORY_SEPARATOR, $v['3d_image']));
                        $FTP->close();
                    }
                }
                if ($v['video_image']) {
                    $attachmentFile = ROOT_PATH . '/public/uploads' . $v['video_image'];
                    if (is_file($attachmentFile))
                    {
                        @unlink($attachmentFile);
                    }
                    //同步删除oss
                    $ftpcfg = get_addon_config('ftp');
                    if ($ftpcfg['ftp_usernmae'] && $ftpcfg['ftp_password']) {
                        $FTP = new \addons\ftp\library\Auth($ftpcfg['ftp_host'], $ftpcfg['ftp_port'], $ftpcfg['ftp_usernmae'], $ftpcfg['ftp_password'], $ftpcfg['ftp_ssh'], $ftpcfg['ftp_pasv']);
                        $FTP->del_file(str_replace('/', DIRECTORY_SEPARATOR, $v['video_image']));
                        $FTP->close();
                    }
                }

                $count += $v->delete();
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 删除上传图片
     */
    public function delUpload()
    {
        if ($this->request->isPost()) {
            $sid = input('sid');
            $dbfield = input('dbfield');
            $path = input('path');
            if ($sid && $dbfield) {
                $this->model->save([$dbfield => ''], ['id' => $sid]);
            }
            $attachmentFile = ROOT_PATH . '/public/uploads' . $path;
            if (is_file($attachmentFile))
            {
                @unlink($attachmentFile);
            }
            //同步删除oss
            $ftpcfg = get_addon_config('ftp');
            if ($ftpcfg['ftp_usernmae'] && $ftpcfg['ftp_password']) {
                $FTP = new \addons\ftp\library\Auth($ftpcfg['ftp_host'], $ftpcfg['ftp_port'], $ftpcfg['ftp_usernmae'], $ftpcfg['ftp_password'], $ftpcfg['ftp_ssh'], $ftpcfg['ftp_pasv']);
                $FTP->del_file(str_replace('/', DIRECTORY_SEPARATOR, $path));
                $FTP->close();
            }
            $this->success();
        }
    }
}
